package file;

import ipconfig.Ipconfig;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Vector;

import voSetting.FileVO;

public class FileUpload extends Thread {
	
	Ipconfig ip = new Ipconfig();
	
	long position;
	long current;
	
	Socket socket = null;
	
	Vector <FileTransferPanel> vectorFileTransferPanels = null;
	Vector<FileInfoVO> vector_fileInfo = null;
	
	File file = null;
	FileChannel fileIn = null;
	FileChannel fileOut = null;
	FileTransfer fileTransfer = null;
	FileTransferPanel fileTransferPanel = null;
	FileInputStream fileInputStream = null;
	FileOutputStream fileOutputStream = null;
	
	OutputStream os = null;
	ObjectOutputStream oos = null;
	
	InputStream is = null;
	ObjectInputStream ois = null;
	
	String sendUser;
	Vector<String> v_filer = null;
	
	public FileUpload(Socket socket, Vector<FileInfoVO> vector_fileInfo, String sendUser, Vector<String> v_filer, Vector<FileTransferPanel> vectorFileTransferPanels, FileTransfer fileTransfer) {
		
		this.socket = socket;
		this.vector_fileInfo = vector_fileInfo;
		this.sendUser = sendUser;
		this.v_filer = v_filer;
		this.vectorFileTransferPanels = vectorFileTransferPanels;
		this.fileTransfer = fileTransfer;
		
		System.out.println("파일 업로드 스레드");
		for(int i=0; i<this.vector_fileInfo.size(); i++){								
			System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 filename: "+this.vector_fileInfo.get(i).getFileName());
			System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 filepath: "+this.vector_fileInfo.get(i).getFilePath());
			System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 filesize: "+this.vector_fileInfo.get(i).getFileSize()+"Bytes");
		}
		
		try {
			System.out.println("소켓의 데이터 :"+socket);
			System.out.println("서버에 연결되었습니다.");
			
			FileSender fs = new FileSender(socket);
			fs.start();
		} catch (Exception e) {
			System.out.println("서버에 연결이 실패 했습니다.");
		}
	}
	
	@Override
	public void run() {
	}

	class FileSender extends Thread {
		
		Socket socket = null;
		DataOutputStream dos = null;
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		
		FileVO fvo = new FileVO();
		
		boolean flag = true;
		
		public FileSender(Socket socket) {
			
			this.socket = socket;
			try {
				os = socket.getOutputStream();
				oos = new ObjectOutputStream(os);
			} catch (Exception e) {
				e.printStackTrace(); 
			}
		}
		
		@Override
		public void run() {
			ArrayList<FileVO> al = new ArrayList<FileVO>();
			
			for(int i=0; i<vectorFileTransferPanels.size(); i++){
				FileVO fvo = new FileVO();
				String filePath = vectorFileTransferPanels.get(i).filePath;
				String fileName = vectorFileTransferPanels.get(i).fileName;
				int fileSize = (int)vectorFileTransferPanels.get(i).fileSize;
				
				System.out.println("파일명: "+filePath);
				System.out.println("파일 경로: "+fileName);
				System.out.println("파일 용량: "+ fileSize);
				fvo.setPanel_fileName(fileName);
				fvo.setPanel_filePath(filePath);
				fvo.setPanel_fileSize(fileSize);
				fvo.setPanel_size(vectorFileTransferPanels.size());
				al.add(fvo);
			}
			
			for(int i=0; i<vectorFileTransferPanels.size(); i++){
				
				try {
					String filePath = vectorFileTransferPanels.get(i).filePath;
					String fileName = vectorFileTransferPanels.get(i).fileName;
					
					System.out.println("파일 전송 작업을 시작 합니다.");
					
					if(flag){
						System.out.println("값을 보냄");
						oos.writeObject(al);
						flag = false;
					}
					
					System.out.println("파일명 ("+fileName+")을 전송하였습니다.");				
				
					System.out.println("파일 읽으면서 전송합니다.");
					File f = new File(filePath);
					fis = new FileInputStream(f);
					bis = new BufferedInputStream(fis);
					
					int len;
					int count = 0;
					byte[] data = new byte[1024];
					while((len = bis.read(data)) != -1){
						
						oos.write(data, 0, len); // 데이터 전송
						
						// 프로그래스바 셋팅 -------------------------------------------
						position += len;
			        	current = (position*100)/f.length();
			        	System.out.println("프로그레스바 진행도: "+current+"%");
			        	count++;
		        		if(vectorFileTransferPanels.get(i) != null){
		        			vectorFileTransferPanels.get(i).setProgressbar((int)current);
		        		}
		        		//--------------------------------------------------------------
					}
					
					oos.flush();
					bis.close();
					fis.close();
					len = 0; current = 0; position = 0;	// for 루프 돌고 초기화
					
					System.out.println("count : " + count);
					System.out.println("패널 사이즈: "+vectorFileTransferPanels.size());
					
					if(vectorFileTransferPanels.size()-1 <= i){
						System.out.println("전체 파일 전송을 완료 하였습니다.");
						System.out.println("종료합니다.");
						oos.close();
						os.close();
						fileTransfer.dispose();
						
						//업로드한 파일을 DB에 저장합니다.
						fileDTO dto = new fileDTO();
						dto.fileInfoInsert(vector_fileInfo, sendUser, v_filer);
						break;
					}
					
					System.out.println("파일 전송을 완료 하였습니다.");
					System.out.println("보낸 파일의 사이즈: "+f.length()+"Bytes");
					sleep(1000);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

